package com.lelefly.base.serviceImp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.ehcache.search.Results;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.lelefly.base.daoimp.BaseDao;
import com.lelefly.base.daoimp.LeleflyFlyerDao;
import com.lelefly.base.model.AddFlyerBean;
import com.lelefly.base.model.AddOrganizationBean;
import com.lelefly.base.model.Page;
import com.lelefly.base.model.Result;
import com.lelefly.base.po.LeleflyOrganization;
import com.lelefly.base.po.LeleflyOrganizationInfo;
import com.lelefly.base.po.LeleflyOrganizationNum;
import com.lelefly.base.po.LeleflyUser;
import com.lelefly.base.po.RegInfo;
import com.lelefly.base.utils.DateUtils;
import com.lelefly.base.utils.RandomUTils;
import com.lelefly.constant.Constant;
import com.lelefly.db.dbmanager.DBManager;

@Service
public class LeleflyFlyerService extends BaseService {

	@Resource
	private BaseDao baseDao;

	@Resource
	private LeleflyFlyerDao flyerDao;

	public Result<LeleflyOrganization> addOrganizationInfo(String ownerPhone,
			String flyerPhone, String flyerName,String code) {

		Result<LeleflyOrganization> result = new Result<>();

		String codeHql = "from RegInfo where regCode='" + code + "'";
		RegInfo regInfo = (RegInfo) flyerDao.getObjcetReUnique(codeHql);
		if (regInfo == null) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("验证码不正确");
			return result;
		}
		// 查询是否创建飞防队
		String sql = "from LeleflyOrganization as model where organizationOwner='"
				+ ownerPhone + "'";
		LeleflyOrganization organization = flyerDao.getOrganization(sql);
		if (organization == null) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("当前手机号码未创建飞防组织");
			return result;
		}
		// 查询是否已在飞防队表中
		String infoSql = "select count(*) as count from "
				+ "lelefly_organization_info WHERE "
				+ "organization_id=(SELECT organization_id FROM lelefly_organization "
				+ "WHERE organization_owner='" + ownerPhone + "' and organization_state=" + Constant.ORGANIZATION_ACTIVE+ ")"
				+ "and flyer_phone='" + flyerPhone + "'";
		int count = flyerDao.getCount(infoSql);
		if (count > 0) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("当前飞手已存在，请勿重复添加");
			return result;
		}

		// 插入飞防队表
		LeleflyOrganizationInfo info = new LeleflyOrganizationInfo();
		info.setOrganizationId(organization.getOrganizationId());
		info.setOrganizationName(organization.getOrganizationName());
		info.setFlyerName(flyerName);
		info.setFlyerPhone(flyerPhone);

		try {
			flyerDao.saveObject(info);
			result.setState(Constant.HTTP_STATUS_OK);
			result.setMes("插入成功");
		} catch (Exception e) {

			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("插入飞手失败");
		}
		return result;
	}

	/**
	 * 移除飞手逻辑
	 * 
	 * @param flyerBean
	 * @return
	 */
	public Result<LeleflyOrganization> removeFlyer(AddFlyerBean flyerBean) {
		Result<LeleflyOrganization> result = new Result<>();

		// 查询是否创建飞防队
		String sql = "from LeleflyOrganization as model where organizationOwner='"
				+ flyerBean.getOwnerPhone() + "' and organization_state=" + Constant.ORGANIZATION_ACTIVE;
		LeleflyOrganization organization = flyerDao.getOrganization(sql);
		if (organization == null) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("当前手机号码未创建飞防组织");
			return result;
		}
		String delSql = "delete from LeleflyOrganizationInfo where organizationId='" 
		+ organization.getOrganizationId()
				+ "' and flyerPhone='" + flyerBean.getFlyerPhone() + "'";
		flyerDao.deteleObjectbySql(delSql);
		
		result.setState(Constant.HTTP_STATUS_OK);
		result.setMes("删除飞手成功");
		return result;
	}
	
	/**
	 * 查询飞手所属组织信息
	 * @param phoneNo
	 * @return
	 */
	public Result<LeleflyOrganizationInfo> queryOrganization(String phoneNo){
		Result<LeleflyOrganizationInfo> result = new Result<>();
		
		String sql = "select organization_name as organizationName,"
				+ "flyer_phone as flyerPhone,flyer_name as flyerName from lelefly_organization_info "
				+ "where organization_id=(select organization_id from lelefly_organization where organization_owner='" 
				+ phoneNo + "' and organization_state="+Constant.ORGANIZATION_ACTIVE
						+ ")";
		List<LeleflyOrganizationInfo> list = flyerDao.getOrganizationList(sql);
		result.setResultList(list);
		result.setState(Constant.HTTP_STATUS_OK);
		result.setMes("查询成功");
		return result;
	}
	
	/**
	 * 返回所有飞防组织，根据组织注册时间排序
	 * @return
	 */
	public Result<LeleflyOrganization> queryOrganization(Page page){
		
		Result<LeleflyOrganization> result = new Result<>();
		
		try {
			String hql = "from LeleflyOrganization";
			List<LeleflyOrganization> resultList = flyerDao.queryOrganization(hql,page.getPage(),page.getCount());
			result.setState(Constant.HTTP_STATUS_OK);
			result.setMes("查询成功");
			result.setResultList(resultList);
			result.setCurPage(page.getPage());
			result.setAllCount(resultList.size());
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("查询失败");
		}
		return result;
	}
	
	/**
	 * 通过飞防队账号加入飞行队
	 * @param organizationNum
	 * 组织账号号码 
	 * @return
	 */
	public Result addOrganizationByNum(String organizationNum){
		Result result = new Result<>();
		
		String hql = "from LeleflyOrganization where organizationNum='" + organizationNum + "'";
		try {
			LeleflyOrganization organization = (LeleflyOrganization) flyerDao.getObjcetReUnique(hql);
			if (organization == null) {
				result.setState(Constant.HTTP_STATUS_FAIL);
				result.setMes("没有该账号的组织");
				return result;
			}
			
			
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("加入飞防队失败");
		}
		return result;
	}
	
	/**
	 * 创建飞防队
	 * @param organizationBean
	 * @return
	 */
	public Result<LeleflyOrganization> createOrganization(AddOrganizationBean organizationBean){
		
		Result<LeleflyOrganization> result = new Result<>();
		// 查询是不是经销商账号
		String validateSql = "from LeleflyUser as model where phonenumber='" + organizationBean.getOwnerPhone()
				+"'";
		LeleflyUser user = (LeleflyUser) flyerDao.getObjcetReUnique(validateSql);
		if (user == null) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("用户不存在");
			return result;
		}
		String type = user.getType();
		if (StringUtils.equals(type, user.getType())) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("经销商账号不能创建飞防队！");
			return result;
		}
		// 当前号码下是否有创建
		String sql = "select count(*) as count from lelefly_organization"
				+ " where organization_owner='" 
				+ organizationBean.getOwnerPhone() + "'";
		int count = flyerDao.getCount(sql);
		
		if (count > 0) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("你已创建过飞防队，请勿重复创建");
			return result;
		}
		// 取飞防队账号
		String numSql = "select * from lelefly_organization_num limit 1";
		LeleflyOrganizationNum organizationNum = (LeleflyOrganizationNum) flyerDao.getObjcetReUniqueBySql(numSql);
		if (organizationNum == null) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("创建账号失败");
			return result;
		}else {
			String delteSql = "delete from lelefly_organization_num limit 1";
			flyerDao.deteleObjectbySql(delteSql);
		}
		try {
			LeleflyOrganization organization = new LeleflyOrganization();
			organization.setOrganizationOwner(organizationBean.getOwnerPhone());
			organization.setOrganizationId(organizationBean.getOwnerPhone() + System.currentTimeMillis());
			organization.setOrganizationName(organizationBean.getOrganizationName());
			organization.setOrganizationState(Constant.ORGANIZATION_ACTIVE);
			organization.setOrganizationCreator(organizationBean.getCreatePhone());
			organization.setRegisterDate(DateUtils.getCurDate());
			organization.setOrganizationNum(organizationNum.getOrganizationNum());
			
			baseDao.saveObject(organization);
			result.setState(Constant.HTTP_STATUS_OK);
			result.setMes("创建成功");
			List<LeleflyOrganization> list = new ArrayList<>();
			list.add(organization);
			result.setResultList(list);
		} catch (Exception e) {
			e.printStackTrace();
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("创建失败");
		}
		return result;
	}
	
	public LeleflyUser getUser(String phoneNum){
		return DBManager.getInstance().getUser(phoneNum);
	}
	
	public Result sendInvitationMessage(String ownerPhone,String phoneNum){
		Result result = new Result<>();
		try {
			
			// 查询是否已在飞防队表中
			String infoSql = "select count(*) as count from "
					+ "lelefly_organization_info WHERE "
					+ "organization_id=(SELECT organization_id FROM lelefly_organization "
					+ "WHERE organization_owner='" + ownerPhone + "' and organization_state=" + Constant.ORGANIZATION_ACTIVE+ ")"
					+ "and flyer_phone='" + phoneNum + "'";
			int count = flyerDao.getCount(infoSql);
			if (count > 0) {
				result.setState(Constant.HTTP_STATUS_FAIL);
				result.setMes("当前飞手已存在，请勿重复添加");
				return result;
			}
			
			String regInfoHql = "from RegInfo where tel='" + phoneNum + 
					"' and mesType='" + Constant.MES_TYPE_INVITATION + "'";
			RegInfo regInfo = (RegInfo) baseDao.getObjcetReUnique(regInfoHql);
			if (regInfo == null) {
				regInfo = new RegInfo();
				regInfo.setTel(phoneNum);
				regInfo.setCount(1);
				regInfo.setExpiredTime(String.valueOf(System.currentTimeMillis()));
			}else {
				if ((System.currentTimeMillis()-Long.valueOf(regInfo.getExpiredTime()))>=1000*60*60*24) {
					regInfo.setCount(0);
				}
				regInfo.setExpiredTime(String.valueOf(System.currentTimeMillis()));
				regInfo.setCount(regInfo.getCount()+1);
			}
			String code = RandomUTils.fix(String.valueOf((int)(Math.random()*10000+1)), 4);
			regInfo.setRegCode(code);
			
			HashMap<String, Object> mesResult = null;
			CCPRestSDK restAPI = new CCPRestSDK();
			restAPI.init(Constant.SERVER, Constant.PORT);// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
			restAPI.setAccount(Constant.ACCOUNT, Constant.TOKEN);
			restAPI.setAppId(Constant.APPID);// 初始化应用ID
			mesResult = restAPI.sendTemplateSMS(phoneNum, Constant.TEMPLATE_INVITATION_ID, new String[] {regInfo.getRegCode()});
			if (StringUtils.equals("000000", (String)mesResult.get("statusCode"))) {
				HashMap<String, Object> data = (HashMap<String, Object>) mesResult.get("data");
				Set<String> keySet = data.keySet();
				for (String key : keySet) {
					Object object = data.get(key);
					getLogger().info(key + " = " + object);
				}
				
				baseDao.saveOrUpdateObject(regInfo);
				result.setState(Constant.HTTP_STATUS_OK);
				result.setMes("短信验证码发送成功");
				
			}else {
				result.setState(Constant.HTTP_STATUS_FAIL);
				result.setMes((String)mesResult.get("statusMsg"));
				getLogger().info("错误码=" + mesResult.get("statusCode") + " 错误信息= "+ mesResult.get("statusMsg"));
			}
		} catch (Exception e) {
			result.setState(Constant.HTTP_STATUS_FAIL);
			result.setMes("服务器错误");
		}
		
		return result;
	}
}
